# encoding=utf-8
import os
import shutil
from seg_system.application_config import ApplicationConfig
from seg_common import ConsoleService


class FileCleanService:

    @staticmethod
    def clean_multi_batch_cache(project_path: str):
        """无数据库比对什么是最新的token，所以直接暴力删除整个文件夹
        """
        multi_batch_path = os.path.join(project_path, ApplicationConfig.PathConfig.BASE_SAVE_PATH)
        for each_user in os.listdir(multi_batch_path):
            user_path = os.path.join(multi_batch_path, each_user)
            shutil.rmtree(user_path)
            ConsoleService.console_log("用户: {},的缓存已经被清空".format(each_user))


    @staticmethod
    def clean_multi_batch_cache_utils_latest(project_path: str):
        """这个3天删除可能会导致用户上传中的数据被擦除，因此保留用户的最新文件夹
        """
        multi_batch_path = os.path.join(project_path, ApplicationConfig.PathConfig.BASE_SAVE_PATH)

        for each_user in os.listdir(multi_batch_path):
            user_dir = os.path.join(multi_batch_path, each_user)
            each_user_tmp_dir = os.listdir(user_dir)
            each_user_tmp_dir.sort(key=lambda dn: os.path.getmtime(os.path.join(user_dir, dn)))
            # 规则就是保留user_tmp和最新的一个目录
            d_list = []
            for each_wait_delete in each_user_tmp_dir:
                abs_path = os.path.join(user_dir, each_wait_delete)
                if each_wait_delete == ApplicationConfig.PathConfig.USER_TMP_FOLDER:
                    continue
                if each_wait_delete == each_user_tmp_dir[-1]:
                    continue

                shutil.rmtree(abs_path)
                d_list.append(abs_path)
            ConsoleService.console_log("用户: {},的{}缓存已经被清空".format(each_user, str(d_list)), ConsoleService.INFO)


# if __name__ == '__main__':
#     basePath = "/home/tacom/code/Segmentation/web/back"
#     FileCleanService.clean_multi_batch_cache_utils_latest(basePath)
